
package com.tools.cleanmaster.ui.card.ui;

import android.animation.StateListAnimator;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hm.base.android.ui.util.ScreenUtil;
import com.hm.base.android.ui.view.CommonInfoView;
import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.bean.AutoCleanFeature;
import com.tools.cleanmaster.functionpage.FunctionItem;
import com.tools.cleanmaster.scenenew.SceneType;
import com.tools.cleanmaster.ui.view.ToastHelper;

/**
 * 对于优化结果为单一数据的，显示此布局
 * <p>
 * created by wen.yu.gang
 */
public class ResultSingleCardLayout extends CommonInfoView<CleanApplication> {

    public static final String TAG = "NewResultCardLayout";

    public static final String ICON_ID = "icon";
    public static final String BG_ID = "bg";
    public static final String EXTEND_TIME = "extend_time";
    public static final String APPS_COUNT = "apps_count";
    public static final String MEM_COUNT = "mem_count";
    public static final String COOL_COUNT = "cool_count";
    public static final String IS_REAL_HANDLE = "real_handle";

    private RelativeLayout mCardWrapper;
    private View mResultCard;
    private TextView mCleanedCount;
    private TextView mCleanedUnit;

    public String mPageType;
    public static final String PAGE_TYPE_SCENE = "scene_"; // 场景化结果页
    public static final String PAGE_TYPE_CLEAN = "clean_"; // 清理结果页
    public static final String PAGE_TYPE_FUNCTION = "function_"; // 功能入口结果页

    private boolean mAnimationFinished = false;
    private boolean mRecommendCardInstalled = false;
    private boolean mResultCardShowReported = false;
    private View autoCleanGuideLayout;


    @Override
    public StateListAnimator getStateListAnimator() {
        return super.getStateListAnimator();
    }

    public ResultSingleCardLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ResultSingleCardLayout(Context context) {
        super(context);
        init(context);
    }

    public void init(Context context) {
        View view = inflate(context, R.layout.new_result_card_view, this);
        mCardWrapper = view.findViewById(R.id.result_display_wrapper);
        autoCleanGuideLayout = view.findViewById(R.id.auto_clean_layout);
    }

    public void initSceneUI(SceneType type, Bundle data) {
        mPageType = PAGE_TYPE_SCENE;
        findViewById(R.id.new_res_page_scene).setBackgroundResource(data.getInt(BG_ID));
        View cardView = LayoutInflater.from(CleanApplication.getInstance()).inflate(cardLayoutWithSceneType(type), mCardWrapper);
        ImageView resultIcon = cardView.findViewById(R.id.result_icon);
        resultIcon.setImageResource(data.getInt(ICON_ID));

        switch (type) {
            case BATTERY_LOW:
                int seconds = data.getInt(EXTEND_TIME);
                ((TextView) cardView.findViewById(R.id.extend_count)).setText("" + seconds / 60);
                break;
            case BAT_SHARPDEC:
            case BG_CPU_OVERLOAD:
                ((TextView) cardView.findViewById(R.id.apps_count)).setText("" + data.getInt(APPS_COUNT));
                break;
            case NETFRQ_SCREENOFF:
                break;
            case BG_MEM_OVERLOAD:
                ((TextView) cardView.findViewById(R.id.mem_count)).setText("" + data.getLong(MEM_COUNT));
                break;
            case CPU_COOLER:
                ((TextView) cardView.findViewById(R.id.dropd_count)).setText("" + data.getInt(COOL_COUNT));
                break;
        }
    }

    public void initFunctionUI(FunctionItem type, Bundle data) {
        mPageType = PAGE_TYPE_FUNCTION;
        findViewById(R.id.new_res_page_scene).setBackgroundResource(data.getInt(BG_ID));
        View cardView = null;
        if (!data.getBoolean(IS_REAL_HANDLE, true)) {
            cardView = LayoutInflater.from(CleanApplication.getInstance()).inflate(R.layout.function_no_handle_layout, mCardWrapper);
        } else {
            switch (type) {
                case BATTERY:
                case CPUCOOL:
                case BOOSTER:
                    cardView = LayoutInflater.from(CleanApplication.getInstance()).inflate(R.layout.scene_problem_fixed_layout, mCardWrapper);
                    TextView commonText = cardView.findViewById(R.id.common_problem);
                    TextView commonMsg = cardView.findViewById(R.id.common_fixed);
                    if (type == FunctionItem.BATTERY) {
                        commonText.setText(R.string.function_battery_result_text);
                        commonMsg.setText(R.string.function_battery_result_msg);
                    } else if (type == FunctionItem.CPUCOOL) {
                        commonText.setText(R.string.function_cpucool_normal_text);
                        commonMsg.setText(R.string.function_cpucool_normal_msg);
                    } else {
                        commonText.setText(R.string.function_booster_result_test);
                        commonMsg.setText(R.string.function_booster_result_msg);
                    }
                    break;
                case BATTERYOVER:
                    cardView = LayoutInflater.from(CleanApplication.getInstance()).inflate(R.layout.scene_apps_close_layout, mCardWrapper);
                    ((TextView) cardView.findViewById(R.id.apps_count)).setText("" + data.getInt(APPS_COUNT));
                    break;
                case CPUOVER:
                    cardView = LayoutInflater.from(CleanApplication.getInstance()).inflate(R.layout.scene_cpu_cool_layout, mCardWrapper);
                    ((TextView) cardView.findViewById(R.id.dropd_count)).setText("" + data.getInt(COOL_COUNT));
                    break;
                case BOOSTEROVER:
                    cardView = LayoutInflater.from(CleanApplication.getInstance()).inflate(R.layout.scene_mem_clean_layout, mCardWrapper);
                    ((TextView) cardView.findViewById(R.id.mem_count)).setText("" + data.getLong(MEM_COUNT));
                    break;
                default:
                    break;
            }
        }

        if (cardView != null) {
            ImageView resultIcon = cardView.findViewById(R.id.result_icon);
            resultIcon.setImageResource(data.getInt(ICON_ID));
        }

        if (isNeedToShowAutoClean()) {
            sendEmptyMessageDelay(R.id.show_auto_clean_guide, 2000L);
        }
    }


    private boolean isNeedToShowAutoClean() {
        return !imContext.getCleanSharedPrefManager().isAutoCleanEnable(AutoCleanFeature.AUTO_CACHE) &&
                !imContext.getCleanSharedPrefManager().isAutoCleanEnable(AutoCleanFeature.AUTO_MEMORY);
    }

    public void initResultPageUI() {
        View view = LayoutInflater.from(CleanApplication.getInstance()).inflate(R.layout.result_display_layout, mCardWrapper);
        findViewById(R.id.new_res_page_scene).setBackgroundResource(0);
        mPageType = PAGE_TYPE_CLEAN;
        mCleanedCount = view.findViewById(R.id.cleaned_count);
        mCleanedUnit = view.findViewById(R.id.cleaned_unit);
        mResultCard = view.findViewById(R.id.result_title);
    }

    @Override
    public void handleChainMessage(Message message) {
        if (message.what == R.id.result_single_card_fade_out) {
            fadeOutResultCardView();
        } else if (message.what == R.id.show_auto_clean_guide) {
            showAutoCleanGuideLayout();
        } else if (message.what == R.id.show_card_wrapper) {
            showCardWrapperLayout();
        }
    }

    private void showCardWrapperLayout() {

        Animation achieveViewHideAnimation = AnimationUtils.loadAnimation(imContext, R.anim.right_in);
        achieveViewHideAnimation.setFillAfter(true);
        mCardWrapper.startAnimation(achieveViewHideAnimation);

        Animation smartCoolTipViewHideAnimation = AnimationUtils.loadAnimation(imContext, R.anim.right_out);
        smartCoolTipViewHideAnimation.setFillAfter(true);
        autoCleanGuideLayout.startAnimation(smartCoolTipViewHideAnimation);
    }

    private void showAutoCleanGuideLayout() {
        autoCleanGuideLayout.setVisibility(View.VISIBLE);
        TextView mWarnTitle = autoCleanGuideLayout.findViewById(R.id.warn_title);
        TextView mWarnDesc = autoCleanGuideLayout.findViewById(R.id.warn_desc);
        TextView mSmartCoolTipView = autoCleanGuideLayout.findViewById(R.id.smart_cool_button);

        Animation achieveViewAnimation = AnimationUtils.loadAnimation(imContext, R.anim.left_out);
        achieveViewAnimation.setFillAfter(true);
        mCardWrapper.startAnimation(achieveViewAnimation);

        // 文本前拼接图片
        Spannable span = new SpannableString(getResources().getString(R.string.smart_cool_warn_title));
        Drawable warn = getResources().getDrawable(R.drawable.smart_cool_guide_tip);
        warn.setBounds(0, 0, ScreenUtil.dp2px(imContext, 30), ScreenUtil.dp2px(imContext, 25));
        ImageSpan prefixSpan = new ImageSpan(warn, ImageSpan.ALIGN_BASELINE);
        span.setSpan(prefixSpan, 0, 7, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        mWarnTitle.setText(span);

        mWarnDesc.setText(Html.fromHtml(getResources().getString(R.string.smart_cool_warn_desc)));

        mSmartCoolTipView.setVisibility(View.VISIBLE);
        Animation smartCoolTipViewAnimation = AnimationUtils.loadAnimation(imContext, R.anim.left_in);
        smartCoolTipViewAnimation.setFillAfter(true);
        autoCleanGuideLayout.startAnimation(smartCoolTipViewAnimation);

        //点击后，进入自动清理页面
        mSmartCoolTipView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                imContext.getAutoCleanManager().setFeatureEnable(AutoCleanFeature.LOW_MEMORY, true);
                imContext.getAutoCleanManager().setFeatureEnable(AutoCleanFeature.AUTO_MEMORY, true);
                imContext.getAutoCleanManager().setFeatureEnable(AutoCleanFeature.AUTO_CACHE, true);

                ToastHelper.create(imContext, R.string.smart_cool_open_success, Toast.LENGTH_SHORT).show();
                sendEmptyMessageDelay(R.id.show_card_wrapper, 1000L);
            }
        });

    }

    /**
     * mResultCard 淡出
     */
    private void fadeOutResultCardView() {
        fadeOutAnimation(mResultCard, new Animation.AnimationListener() {
            @Override
            public void onAnimationEnd(Animation animation) {
                mAnimationFinished = true;
            }

            @Override
            public void onAnimationStart(Animation animation) {
                mAnimationFinished = false;
                mResultCard.setVisibility(INVISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

    public void startRecommendCardAnimation() {
        if (!mResultCardShowReported) {
            mResultCardShowReported = true;
        }

        sendEmptyMessageDelay(R.id.result_single_card_fade_out, 2000L);
    }

    public static int cardLayoutWithSceneType(SceneType type) {
        switch (type) {
            case BATTERY_LOW:
                return R.layout.scene_battery_layout;
            case BAT_SHARPDEC:
            case BG_CPU_OVERLOAD:
                return R.layout.scene_apps_close_layout;
            case NETFRQ_SCREENOFF:
                return R.layout.scene_problem_fixed_layout;
            case BG_MEM_OVERLOAD:
                return R.layout.scene_mem_clean_layout;
            case CPU_COOLER:
                return R.layout.scene_cpu_cool_layout;
            default:
                return 0;
        }
    }

    public void fillWrapperView(View v) {
        mCardWrapper.setGravity(Gravity.CENTER_HORIZONTAL);
        mCardWrapper.addView(v);
    }

    public void fillADView(View view) {
        FrameLayout adLayout = findViewById(R.id.advert_container);
        adLayout.addView(view);
    }

    public void setDisplayResult(String size, String unit) {
        mCleanedCount.setText(size);
        mCleanedUnit.setText(unit);
    }

    public void fadeOutAnimation(View view, Animation.AnimationListener listener) {
        Animation fadeOut = AnimationUtils.loadAnimation(getContext(), R.anim.result_fade_out);
        fadeOut.setAnimationListener(listener);
        view.startAnimation(fadeOut);
    }

    public void onActivityDestroy(Context context) {

    }

    public void onActivityResume() {
    }
}
